import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import Layout from '@/layout/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: { title: '仪表盘', icon: 'HomeFilled' }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('@/views/user/index.vue'),
          meta: { title: '用户管理', icon: 'User', roles: ['ADMIN'] }
        },
        {
          path: 'role',
          name: 'Role',
          component: () => import('@/views/role/index.vue'),
          meta: { title: '角色管理', icon: 'UserFilled', roles: ['ADMIN'] }
        },
        {
          path: 'attendance',
          name: 'Attendance',
          redirect: '/attendance/rule',
          meta: { title: '考勤管理', icon: 'Calendar' },
          children: [
            {
              path: 'rule',
              name: 'AttendanceRule',
              component: () => import('@/views/attendance/rule/index.vue'),
              meta: { 
                title: '考勤规则', 
                icon: 'Setting', 
                roles: ['ADMIN'],
                activeMenu: '/attendance/rule'
              }
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/register/index.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token
  const userRole = userStore.getRole()

  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }

  if (!token) {
    next('/login')
    return
  }

  // 检查是否是管理员
  if (userRole !== 'ADMIN') {
    ElMessage.error('只有管理员才能访问管理系统')
    next('/login')
    return
  }

  next()
})

export default router 